/**
 * 是否要连接
 * @returns
 */
function isConnect(e){
	if($(e).val()==0){
		disconnect();
	}else{
		connect();
	}
}

var ws=null;

/**
 * 连接WebSocket
 * @returns
 */
function connect(){
	if("WebSocket" in window){
		ws=new WebSocket("ws://localhost:8080/socket/"+$("body").attr("data-id"));
	}else if("MozWebSocket" in window){
		ws=new MozWebSocket("ws://localhost:8080/socket/"+$("body").attr("data-id"));
	}else{
		layer.alert("该浏览器不支持websocket");
	}
	
	//接收服务器发来的消息
	ws.onmessage=function(evt){
		//更新新消息数量
		refreshNotice();
		//console.log(evt);
		//alert(evt.data);
		layer.open({
			  type: 1,
			  title: "通知提醒",
			 // closeBtn: 0, //不显示关闭按钮
			  shade: [0],
			  area: ['340px', '215px'],
			  offset: 'rb', //右下角弹出
			  content: "新通知："+evt.data
			});
		
	}
	
	//连接关闭时触发
	ws.onclose=function(evt){
		$("#connect-state").css("color","red");
		$("#connect-state").next().val(0);
		console.log(">>>>>>>>>>>>>>>>>>>websocket连接关闭");
	}
	
	//连接开启时触发
	ws.onopen=function(evt){
		$("#connect-state").css("color","#008d4c");
		$("#connect-state").next().val(1);
		console.log("<<<<<<<<<<<<<<<<<<<websocket连接成功");
	}
}

/**
 * 关闭连接
 * @returns
 */
function disconnect(){
	if(ws!=null){
		ws.close();
	}
}

/**
 * 发送消息
 * @returns
 */
function sendMsg(text){
	ws.send(text);
}

/**
 * 发送给指定方
 */
function sendMsgToOne(message,userId){
	$.getJSON("/socket/sendone?message="+message+"&userId="+userId,function(data){
		alert(data);
	});
}

/**
 * 发送给所有在线用户
 * @returns
 */
function sendMsgToAll(message){
	$.getJSON("/socket/sendall?message="+message,function(data){
		alert(data);
	});
}